<?php
namespace App\Http\Controllers\Company;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\CompanyContactsCreateClientRequest;
use App\Http\Requests\CompanyContactsCreateFamilyRequest;
use App\Http\Requests\CompanyContactsMessageSubmitRequest;
use App\Libraries\msg\Msg;
use App\Libraries\msg\Push;
use App\Models\ClientUser;
use App\Models\ClientUserFamily;
use App\Models\ClientUserHouse;
use App\Models\ClientUserRelationship;
use App\Models\ClientUserMessage;
use App\Models\ClientUserMessagesTemplate;
use App\Models\House;
use App\Models\HouseDistrict;
use App\Models\HouseDistrictCar;
use App\Models\HouseDistrictCosts;
use App\Models\HouseDistrictOwner;
use Illuminate\Support\Facades\DB;

class ContactsController extends CommonController {

	public function index(BasicRequest $request){
        $house_id = $request->input('house_id',0);
        $keyword = $request->input('keyword');
        $h_ids = explode(',',$this->ship->house_id);
        $house = HouseDistrict::select('id','name','type')->whereIn('id',$h_ids)->get();
        $data = House::leftJoin('house_district_owner','house.house_id','=','house_district_owner.house_id')
            ->leftJoin('client_user_roles_house as roles_house','house.house_id','=','roles_house.house_id')
            ->groupBy('house.house_id')
            ->select('house.house_id as id','house.house_sn as realname','house_district_owner.mobile','house_district_owner.realname as username')
            ->when($keyword,function($query) use($keyword){
                $query->where('house_district_owner.realname','like','%'.$keyword.'%')
                    ->orWhere('house.house_sn','like','%'.$keyword.'%')
                    ->orWhere('house_district_owner.mobile','like','%'.$keyword.'%');
            })
            ->where(function($query){
                if($this->ship->type==5){
                    //分区经理
                    $query->where('house.partition_id','=',$this->ship->house_id);
                }else if($this->ship->type==4){
                    //管家
                    $query ->where('roles_house.uid','=',$this->uid);
                }else if($this->ship->type==3){
                    //主管
                    $uid_in = ClientUserRelationship::treeChildrenOne($this->ship->uid,3)->pluck('uid');
                    $query ->whereIn('roles_house.uid',$uid_in)->groupBy('roles_house.house_id');
                }else if($this->ship->type==2){
                    //项目经理
                    $query->where('house.village_id','=',$this->ship->house_id);
                }else if($this->ship->type=1){
                    $h_ids=explode(',',$this->ship->house_id);
                    $query->whereIn('house.village_id',$h_ids);
                }
            })->when($house_id,function($query) use ($house_id){
                //根据house_id获取类别查询
                if($house_id>0) {
                    $house_type = HouseDistrict::where('id', '=', $house_id)->value('type');
                    switch ($house_type) {
                        case 2:
                            $query->where('house.village_id','=',$house_id);
                            break;
                        case 3:
                            $query->where('house.budding_id','=',$house_id);
                            break;
                        case 4:
                            $query->where('house.unit_id','=',$house_id);
                            break;
                        case 5:
                            $query->where('house.floor_id','=',$house_id);
                            break;
                        case 6:
                            $query->where('house.house_id','=',$house_id);
                            break;
                        case 7:
                            $query->where('house.partition_id','=',$house_id);
                            break;
                    }
                }
            })->orderBy('realname','asc')->pages()->each(function($v,$k){
                $is_register = ClientUserHouse::where(['house_id'=>$v->id])->first();
                $v->is_resgiter = $is_register ? 1 : 0;
                $v->avatar = $is_register ? ClientUser::where(['id'=>$is_register->uid])->value('avatar'):"http://api.hcysq.cn/images/avatar.png";
            });

          $return = [
              'house'		=> $house,
              'client'	=> $data,
          ];
          return json_success('OK',$return);
     }

     //获取房间列表
     public function contacts_house_list(BasicRequest $request){
          $house_id = $request->input('house_id',$this->ship->house_id);
		  $house_type = HouseDistrict::where(['id'=>$house_id])->value('type');

          $house = House::leftJoin('client_user_roles_house as roles_house','house.house_id','=','roles_house.house_id')
              ->where(function($query){
                   if($this->ship->type==4){
                        //管家
                        $query ->where('roles_house.uid','=',$this->uid);
                   }else if($this->ship->type==3){
                        //主管
                        $uid_in = ClientUserRelationship::treeChildrenOne($this->ship->uid,3)->pluck('uid');
                        $query ->whereIn('roles_house.uid',$uid_in)->groupBy('roles_house.house_id');
                   }
				   
              })
			  ->when($house_type,function($query) use($house_type,$house_id){
				  switch ($house_type){
					  case 2:
						$query->leftJoin('house_district','house.partition_id','=','house_district.id')->select('house_district.id','house_district.name')->where('house_district.parent_id','=',$house_id)->groupBy('house.partition_id');
						break;
					  case 7:
						$query->leftJoin('house_district','house.budding_id','=','house_district.id')->select('house_district.id','house_district.name')->where('house_district.parent_id','=',$house_id)->groupBy('house.budding_id');
						break;
					  case 3:
					    $query->leftJoin('house_district','house.unit_id','=','house_district.id')->select('house_district.id','house_district.name')->where('house_district.parent_id','=',$house_id)->groupBy('house.unit_id');
						break;
					  case 4:
					    $query->leftJoin('house_district','house.floor_id','=','house_district.id')->select('house_district.id','house_district.name')->where('house_district.parent_id','=',$house_id)->groupBy('house.floor_id');
						break;
					  case 5:
					    $query->leftJoin('house_district','house.house_id','=','house_district.id')->select('house_district.id','house_district.name')->where('house_district.parent_id','=',$house_id)->groupBy('house.house_id');
						break;
					  default:
						break;
				  }
			  })->get();

          return json_success('OK',$house);
     }

	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 业主详情
	 */
	public function detail(BasicRequest $request){
	    $id = $request->input('id');
	    $date = HouseDistrictOwner::where(['house_id'=>$id])->select('realname as username','mobile')->first();
	    if(!$date){
	        return json_error('找不到该用户');
        }
        $date->house = House::where('house_id',$id)->select('house_detail as name_long','house_detail','id','house_sn')->first();

        $date->family = ClientUserHouse::where(['primary'=>0,'house_id'=>$id])
            ->rightJoin('client_user','client_user.id','=','client_user_house.uid')
            ->where(['client_user.type'=>3])
            ->where(['client_user.status'=>1])
            ->select('username','username as realname','mobile','uid as id','avatar')
            ->get();

        $master = ClientUserHouse::where(['house_id'=>$id])
            ->rightJoin('client_user','client_user.id','=','client_user_house.uid')
            ->select('username','mobile','uid as id','avatar')
            ->where(['client_user.type'=>1])
            ->orderBy('primary','desc')
            ->first();
        $date->master = $master?:(new \stdClass());
        $date->id = $master->id ?:'';
        $date->avatar = $master->avatar?:'';
		return json_sussess_obj('OK',$date);
	}
	
	/**
	 * @param CompanyContactsCreateClientRequest $request
	 * @throws ApiException
	 * @return array
	 * 添加业主，绑定房屋
	 */
	public function create_client(CompanyContactsCreateClientRequest $request){
		$house_id = $request->input('house_id');
		$realname = $request->input('realname');
		$mobile = $request->input('mobile');
		$uid = ClientUser::where(['mobile'=>$mobile])->value('id');
		// 判断是否是业主，已后台录入为准
		$exists = HouseDistrictOwner::where(['house_id'=>$house_id,'mobile'=>$mobile])->exists();
		if(!$exists){
			$var = HouseDistrictOwner::create([
				'house_id'		=> $house_id,
				'realname'		=> $realname,
				'mobile'		=> $mobile,
			])->id;
		}else{
			throw new ApiException('此手机号已经是该房屋的业主');
		}
		if(empty($uid)){
			// 帮注册，用户名密码都是手机号
//			$clientUser = new ClientUser();
//			$var = $clientUser->register($mobile,$mobile,$mobile);
		}else{
			// 如果注册了，自动绑定房屋
			ClientUserHouse::create([
				'uid'		=> $uid,
				'house_id'	=> $house_id,
			]);
		}
		return json_return($var,'','添加成功');
	}
	
	/**
	 * @param CompanyContactsCreateFamilyRequest $request
	 * @return array
	 * 添加家属，与业主的附属关系
	 */
	public function create_family(CompanyContactsCreateFamilyRequest $request){
		$house_id = $request->input('house_id');
		$realname = $request->input('realname');
		$mobile = $request->input('mobile');
		$relationship = $request->input('relationship','其他');	// 与业主的关系，如 女儿

        $uid = ClientUser::where(['mobile'=>$mobile])->value('id');
        //判断是否有此手机号
        $exists = HouseDistrictOwner::where(['house_id'=>$house_id,'mobile'=>$mobile])->exists();
        if($exists){
            return json_error('用户已是这间房屋的家属');
        }
        $id = HouseDistrictOwner::create([
            'house_id'=> $house_id,
            'realname'=>$realname,
            'mobile'=> $mobile,
            'if_primary'=>0,
            'relationship'=>$relationship,
            'remarks'=>'管家添加家属'
        ])->id;
        if(!empty($uid)){
            // 如果注册了，自动绑定房屋
            ClientUserHouse::create([
                'uid'		=> $uid,
                'house_id'	=> $house_id,
            ]);
        }
		return json_return($id,'','添加成功');
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 给用户发送推送/短信的模板内容
	 */
	public function message(BasicRequest $request){
		$data = ClientUserMessagesTemplate:: where('house_id','=',$this->ship->village_id)->get();

		return json_success('OK',$data);
	}
	
	/**
	 * @param CompanyContactsMessageSubmitRequest $request
	 * @return array
	 * 给用户发送消息
	 */
	public function message_submit(CompanyContactsMessageSubmitRequest $request){
		$uid = $request->input('uid');	// 收信人uid
		$type = $request->input('type','0');	// 0推送，1短信，2站内消息
		$title = $request->input('title');	// 消息标题
		$content = $request->input('content');	// 消息内容
		
		switch($type){
			case '0' :
				$push = new Push();
				$push->queue($uid,$title,$content,['messages_type_id'=>3]);
				break;
			case '1' :
				$mobile = ClientUser::where(['id'=>$uid])->value('mobile');
				$house = HouseDistrict::findOrNew(ClientUserHouse::where(['uid'=>$uid])->value('house_id'))->detail()->name_long;
				send_message($mobile,$title,[$house,$content]);
				break;
			case '2' :
				ClientUserMessage::send($uid,$title,$content,3);
				break;
		}
		return json_success('消息发送成功');
	}
}